package edu.mju.eduuser.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import edu.mju.commonutils.JwtUtils;
import edu.mju.eduuser.entity.StudyMember;
import edu.mju.eduuser.service.StudyMemberService;
import edu.mju.eduuser.utils.ConstantGiteeUtils;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.request.AuthGiteeRequest;
import me.zhyd.oauth.request.AuthRequest;
import me.zhyd.oauth.utils.AuthStateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: wyp
 * @Date: 2020/11/26 8:40
 */
@CrossOrigin
@Controller
@RequestMapping("/api/ucenter/gitee")
public class GiteeApiController {

    @Autowired
    private StudyMemberService studyMemberService;

//    @GetMapping("/callback")
//    public String callback(String code,String state){
//        try {
//            //通过code请求码云认证服务器
//            String baseAccessTokenUrl = "https://gitee.com/oauth/token" +
//                    "?grant_type=authorization_code" +
//                    "&code=%s" +
//                    "&client_id=%s" +
//                    "&redirect_uri=%s" +
//                    "&client_secret=%s";
//
//            //拼接参数
//            String accessTokenUrl = String.format(
//                    baseAccessTokenUrl,
//                    code,
//                    ConstantGiteeUtils.GITEE_CLIENT_ID,
//                    ConstantGiteeUtils.GITEE_REDIRECT_URL,
//                    ConstantGiteeUtils.GITEE_CLIENT_SECRET
//            );
//
//            //请求拼接参数，返回access_token
//            String post = HttpClientUtils.post(accessTokenUrl, null, "application/json", "UTF-8", 80000, 80000);
//
//            //解析access_token
//            Gson gson = new Gson();
//            HashMap mapAccessToken = gson.fromJson(post,HashMap.class);
//            String access_token = (String)mapAccessToken.get("access_token");
//
//            //根据获取的access_token，请求用户数据
//            String getUserInfoUrl = "https://gitee.com/api/v5/user" +
//                    "?access_token=%s";
//            //添加参数
//            String getUserInfo = String.format(getUserInfoUrl,access_token);
//            //发送请求，赋值给accessTokenInfo
//            String accessTokenInfo = HttpClientUtils.get(getUserInfo);
//
//            HashMap mapGiteeAccessToken =gson.fromJson(accessTokenInfo,HashMap.class);
//
//            String giteeId =String.valueOf (mapGiteeAccessToken.get("id"));
//
//            //根据giteeid判断是否有相同的用户
//            StudyMember member = studyMemberService.getGiteeIdMember(giteeId);
//
//            //没有用户，则注册
//            if(member==null){
//                String nickname = (String) mapGiteeAccessToken.get("name");
//                String headimgurl = (String) mapGiteeAccessToken.get("avatar_url");
//
//                member = new StudyMember();
//                member.setGiteeid(giteeId);
//                member.setNickname(nickname);
//                member.setAvatar(headimgurl);
//                studyMemberService.save(member);
//            }
//
//            //使用jwt根据Member对象生成token字符串
//            String jwtToken = JwtUtils.getJwtToken(member.getId(),member.getNickname());
//
//            return "redirect:http://localhost:3000?token="+jwtToken;
//        }catch(Exception e){
//            e.printStackTrace();
//            throw new StuException(20001,"码云登录失败");
//        }
//    }

//    @GetMapping("/login")
//    public String getGitee(){
//        //固定地址+参数
//        String baseUrl = "https://gitee.com/oauth/authorize" +
//                "?client_id=%s" +
//                "&redirect_uri=%s" +
//                "&response_type=code";
//
//        //对redirect_url进行编码
//        String redirectUrl = ConstantGiteeUtils.GITEE_REDIRECT_URL;
//        try {
//            redirectUrl = URLEncoder.encode(redirectUrl, "utf-8");
//        }catch(Exception e) {
//            e.printStackTrace();
//        }
//
//        //向baseUrl设值
//        String mju = String.format(baseUrl,ConstantGiteeUtils.GITEE_CLIENT_ID,redirectUrl);
//        return "redirect:"+mju;
//    }

    AuthRequest authRequest = null;
    //使用JustAuth实现
    @GetMapping("/login")
    public String getGitee(){
        //创建授权request
        AuthRequest authRequest = new AuthGiteeRequest(AuthConfig.builder()
                .clientId(ConstantGiteeUtils.GITEE_CLIENT_ID)
                .clientSecret(ConstantGiteeUtils.GITEE_CLIENT_SECRET)
                .redirectUri(ConstantGiteeUtils.GITEE_REDIRECT_URL)
                .build());

        //生成第三方平台的授权链接
        String authorize = authRequest.authorize(AuthStateUtils.createState());

        return "redirect:"+authorize;
    }

    //创建授权request
    private AuthRequest getAuthRequest() {
        return new AuthGiteeRequest(AuthConfig.builder()
                .clientId(ConstantGiteeUtils.GITEE_CLIENT_ID)
                .clientSecret(ConstantGiteeUtils.GITEE_CLIENT_SECRET)
                .redirectUri(ConstantGiteeUtils.GITEE_REDIRECT_URL)
                .build());
    }


    @GetMapping("/callback")
    public String callback(AuthCallback callback){
        //创建授权request
        AuthRequest authRequest = getAuthRequest();
        //使用callback内的参数code登录 框架已封装此操作。返回数据结果
        AuthResponse authResponse = authRequest.login(callback);

        //将数据结果取出
        AuthUser user = (AuthUser) authResponse.getData();
        String uuid = user.getUuid();
        String nickname = user.getNickname();
        String avatar = user.getAvatar();

        //根据giteeid判断是否有相同的用户
        StudyMember member = studyMemberService.getGiteeIdMember(uuid);

        //没有用户，则注册
        if(member==null){

            member = new StudyMember();
            member.setGiteeid(uuid);
            member.setNickname(nickname);
            member.setAvatar(avatar);
            studyMemberService.save(member);
        }

        //使用jwt根据Member对象生成token字符串
        String jwtToken = JwtUtils.getJwtToken(member.getId(),member.getNickname());

        return "redirect:http://localhost:3000?token="+jwtToken;
    }



}
